package com.moodincode.taskcenter.script;

import com.alibaba.fastjson.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * json工具类
 * @author moodincode
 */
public class JsonUtil {
    private static Pattern linePattern = Pattern.compile("_(\\w)");
    private static Pattern humpPattern = Pattern.compile("[A-Z]");
    /**
     * 转字符串
     * @param object
     * @return
     */
    public static String toString(Object object){
        return JSONObject.toJSONString(object);
    }

    /**
     * 下划线转驼峰
     * @param object
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static Object underlineToHump(Object object) throws InstantiationException, IllegalAccessException {
        if(object==null){
            return null;
        }else if(object instanceof Map){
           Map data=(Map) object;
           Map result=data.getClass().newInstance();

            Set<String> set = data.keySet();
            for (String key : set) {
                Object v = data.get(key);
                if(v instanceof Map ||v instanceof List){
                    result.put(lineToHump(key),underlineToHump(v));
                }else {
                    result.put(lineToHump(key),v);
                }

            }
            return result;

        }else if(object instanceof List){
            List data=(List)object;
            List result=data.getClass().newInstance();
            for (Object datum : data) {
                result.add(underlineToHump(datum));
            }
            return result;
        }
        return object;
    }

    /** 下划线转驼峰 */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /** 驼峰转下划线 */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
